<?php


namespace app\admin\service;


use app\utils\redis\RedisCache;
use app\utils\redis\RedisKey;
use app\utils\redis\RedisObj;

class TimeTaskService
{

    /**
     * 根据每天ip统计广告和文章点击数，并重置
     * @param int $db
     * @param string $prefix_redis_key
     * @return array
     */
    public function cleanArticleAndIdTodayIpNum(string $prefix_redis_key){
        // 获取指定前缀的key
        [$id_num_arr, $keys, $_] = $this->getIdNumAndIds($prefix_redis_key);
        RedisCache::dDeleteKey(RedisObj::STATISTICS_DB, $keys);
        return $id_num_arr;
    }

    /**
     * 通过指定前缀在redis中找出对应的统计数据
     * @param string $prefix_redis_key
     * @return array
     */
    private function getIdNumAndIds(string $prefix_redis_key) {
        // 获取指定前缀的key
        $keys = RedisCache::rFindKeysByPrefix(RedisObj::STATISTICS_DB, $prefix_redis_key);
        // 保存['id'=>id, 'num'=>click_num]集合
        $id_num_arr = [];
        $ids = [];
        foreach ($keys as $redis_key){
            $id = (int)explode('_', $redis_key)[3];
            // redis_key获取对应的value的长度
            $value_len = RedisCache::rSetLen(RedisObj::STATISTICS_DB, $redis_key);
            array_push($id_num_arr, [
                'id'=> $id,
                'num'=> $value_len,
            ]);
            array_push($ids, $id);
        }
        return [$id_num_arr, $keys, $ids];
    }

    /**
     * 在redis获取今天文章点击数
     * @return array
     */
    public function getTodayArticleStatisticsByRedis() {
        return $this->getIdNumAndIds(RedisKey::$articleReadNumKey);
    }

    /**
     * 在redis获取今天广告点击数
     * @return array
     */
    public function getTodayAdStatisticsByRedis() {
        return $this->getIdNumAndIds(RedisKey::$adReadNumKey);
    }
}